//
//  ViewController.swift
//  BLEBackgroundScan
//
//  Created by YangGump on 2016/11/14.
//  Copyright © 2016年 YangGump. All rights reserved.
//

import UIKit
import CoreBluetooth

class ViewController: UIViewController, CBCentralManagerDelegate, CBPeripheralDelegate {
    
    @IBOutlet weak var label: UILabel!
    // 添加属性
    var manager: CBCentralManager!
    var peripheral: CBPeripheral!
    // 保存搜到的蓝牙设备
    var deviceList:NSMutableArray = NSMutableArray()
    // 服务和特征的UUID
    let kServiceUUID = [CBUUID(string:"FFF0")]
    
    var firstFlag: Bool = true
    var deviceUUID = [CBUUID(string:"FFF0")]
    var timer: Timer = Timer()
    var currentRunLoop: CFRunLoop!
    var count: Int = 0
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        // 1.创建一个中央对象
        self.manager = CBCentralManager(delegate:self, queue:nil)
        self.firstFlag = true;
        self.count = 0;
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


    @IBAction func onClick(_ sender: Any) {
        label.text = "hello World!";
    }
    
    // 2.检查运行这个App的设备是不是支持BLE代理方法
    func centralManagerDidUpdateState(_ central: CBCentralManager) {
        if #available(iOS 10.0, *) {
            switch central.state{
            case CBManagerState.unauthorized:
                print("This app is not authorised to use Bluetooth low energy")
            case CBManagerState.poweredOff:
                print("Bluetooth is currently powered off.")
            case CBManagerState.poweredOn:
                print("Bluetooth is currently powered on and available to use.")
                self.manager.scanForPeripherals(withServices:kServiceUUID, options: [CBCentralManagerScanOptionAllowDuplicatesKey:true]);
            default:break
            }
        } else {
            switch central.state {
            case .poweredOn:
                // 扫描周边蓝牙外设
                // 写nil表示扫描所有蓝牙外设，如果传上面的kServiceUUID，那么只能扫描出这个服务的外设。
                // CBCentralManagerScanOptionAllowDuplicatesKey表示是否可以重复扫描重名设备
                self.manager.scanForPeripherals(withServices:kServiceUUID, options: [CBCentralManagerScanOptionAllowDuplicatesKey:true]);
                print("蓝牙已打开，请扫描外设");
                label.text = "蓝牙已打开，请扫描外设";
            case .unauthorized:
                print("这个应用程序是无权使用蓝牙低功耗")
                label.text = "这个应用程序是无权使用蓝牙低功耗"
            case .poweredOff:
                print("蓝牙目前关闭状态")
                label.text = "蓝牙目前关闭状态"
            default:
                print("中央管理器没有改变状态")
                label.text = "中央管理器没有改变状态"
            }
        }
    }
    
    // 3.查到外设后，停止扫描
    // 广播，扫描的响应数据保存在advertisementData中，可以通过CBA来访问它
    func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
        if (self.firstFlag) {
            print("有扫描到BLE设备 \(peripheral.description)")
            print("广播数据 \(advertisementData.description)")
            self.manager.stopScan();
            self.deviceUUID = [CBUUID(string:peripheral.identifier.uuidString)]
            // printf("将要使用的UUID \(self.deviceUUID)")
            // self.deviceList.addObjects(from: peripheral) // 此后可以加入调用连接
            self.firstFlag = false;
            self.timer = Timer.scheduledTimer(timeInterval: 5.0, target: self, selector: #selector(ViewController.update), userInfo: nil, repeats: true)
            
            RunLoop.current.add(self.timer, forMode:RunLoopMode.defaultRunLoopMode)
            
        } else {
            print("有扫描到BLE设备 \(peripheral.description)")
            print("广播数据 \(advertisementData.description)")
            self.manager.stopScan();
        }
    }
    
    public func update() {
        self.manager.scanForPeripherals(withServices:kServiceUUID, options: [CBCentralManagerScanOptionSolicitedServiceUUIDsKey:self.deviceUUID, CBCentralManagerScanOptionAllowDuplicatesKey:true]);
        print("重新开始扫描")
        self.count += 1
        self.label.text = "计数 \(self.count)"
    }
}

